#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>

widget::widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::widget)
{
    ui->setupUi(this);

    serialport = new QSerialPort();//实例化串口对象

    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
        ui->comboBox->addItem(info.portName());
    }
    //
    connect(serialport,SIGNAL(readyRead()),SLOT(readData()));
}

widget::~widget()
{
    delete ui;
}


void widget::on_pushButton_3_clicked(bool checked)
{
    if(checked){
    serialport->setPortName(ui->comboBox->currentText());
    serialport->setBaudRate(ui->comboBox_2->currentText().toInt());
    serialport->setStopBits(QSerialPort::StopBits(ui->comboBox_3->currentText().toInt()));
    serialport->setDataBits(QSerialPort::DataBits(ui->comboBox_4->currentText().toInt()));
    switch (ui->comboBox_5->currentIndex()) {
    case 0:
        serialport->setParity(QSerialPort::Parity::NoParity);
        break;
    case 1:
        serialport->setParity(QSerialPort::Parity::OddParity);
        break;
    case 2:
        serialport->setParity(QSerialPort::Parity::EvenParity);
        break;
    default:
        break;
    }
    serialport->setFlowControl(QSerialPort::NoFlowControl);
    if( !serialport->open(QIODevice::ReadWrite))
    {
        QMessageBox::about(this,"错误","串口打开失败可能被占用了");
        return;
    }
        ui->comboBox->setEnabled(false);
        ui->comboBox_2->setEnabled(false);
        ui->comboBox_3->setEnabled(false);
        ui->comboBox_4->setEnabled(false);
        ui->comboBox_5->setEnabled(false);
        ui->pushButton_3->setText("关闭串口");
    }
    else{
        serialport->close();
        ui->comboBox->setEnabled(true);
        ui->comboBox_2->setEnabled(true);
        ui->comboBox_3->setEnabled(true);
        ui->comboBox_4->setEnabled(true);
        ui->comboBox_5->setEnabled(true);
        ui->pushButton_3->setText("打开串口");
    }
}

void widget::readData()
{
    QByteArray serialArray = serialport->readAll();
    ui->textBrowser->insertPlainText(serialport->readAll());

    QByteArray data1 = ui->textEdit_3->toPlainText().toUtf8();
    QByteArray data2 = ui->textEdit_4->toPlainText().toUtf8();
    QString data3 = ui->textEdit_5->toPlainText();

    char *data_p = serialArray.data();
    for(uint8_t i;i<serialArray.size();i++)
    {
        if(data_p[i] == data1.toInt() && data_p[i+1] == data2.toInt());
        {
            serialport->write(data3.toStdString().data(),3);
        }
    }
}


void widget::on_pushButton_6_clicked()
{
    ui->textEdit_3->setEnabled(false);
    ui->textEdit_4->setEnabled(false);
}


void widget::on_pushButton_7_clicked()
{
    ui->textEdit_3->setEnabled(true);
    ui->textEdit_4->setEnabled(true);
}


void widget::on_pushButton_clicked()
{
    QString data3 = ui->textEdit_5->toPlainText();
    ui->textBrowser->setPlainText(data3);
}

